import { NOTINITROUTE } from '@/constants'
import { getUserInfoAPI } from '@/request'
// import type { User01Response } from '@fxl/request'
import { getSetting } from '@/settings'
import WebTracing from '@web-tracing/vue3'
import type { App } from 'vue'
import { useUserStore, getUrlQuery } from '@/utils'

export function initTracing(app: App) {
  const userStore = useUserStore()

  const { title = '' } = getSetting()

  const pathname = window.location.pathname

  // 绑定页面不需要获取用户信息，好像这个页面调 transfer 接口会报错
  // if (pathname.includes('/bind')) {
  //   tracingInit(getUrlQuery())
  //   return
  // }

  if (!NOTINITROUTE.some((path) => pathname.includes(path))) {
    getUserInfoAPI({ isHideToast: true }).then((res) => {
      userStore.change(res)

      if (res?.address && res?.address?.contactPhone) {
        try {
          const decodedAddress = { ...res.address }
          decodedAddress.contactPhone = atob(res.address.contactPhone)
          userStore.changeAddress(decodedAddress)
        } catch (e) {
          userStore.changeAddress(res.address)
        }
      } else {
        userStore.changeAddress(res.address)
      }

      tracingInit(res)
    })
  }
  if (pathname.includes('/bind')) {
    const channel: any = {
      XMJR001: 14001,
    }
    const { channelCode } = getUrlQuery()
    if (channelCode) {
      tracingInit({ channelCode, channelId: channel[channelCode] })
    }
  }

  function tracingInit(obj: any) {
    if (import.meta.env.VITE_ENV != 'dev') {
      const { channelCode, channelId, memberCode, memberId, userId } = obj

      if (!channelId) return

      const strChannelId = String(channelId)

      app.use(WebTracing, {
        dsn: `${import.meta.env.VITE_PROXY_URL}tracing/send/${strChannelId}`,
        appCode: strChannelId,
        appName: title,
        userUuid: userId, // 用户id
        ext: { channelCode, strChannelId, memberCode, memberId, userId },
        debug: true, // 是否开启触发事件时控制台输出
        pv: true,
        // 当 performance 为布尔值时其内部所有属性都为此布尔值
        performance: {
          firstResource: false, // 是否采集首次进入页面的数据
          server: false, // 是否采集接口请求
        },
        error: true, // 当 error 为布尔值时其内部所有属性都为此布尔值: 是否采集异常数据 | 是否采集报错接口数据
        event: true, // 是否采集点击事件
        cacheMaxLength: 1, // 上报数据最大缓存数
        cacheWatingTime: 500, // 上报数据最大等待时间(ms)
        ignoreRequest: [], // 请求类型事件过滤
        sendTypeByXmlBody: true, // 是否强制指定发送形式为xml，body请求方式
      })
    }
  }
}
